<template>
  <mu-flex direction="column" style="height: 100%;">
    <!--顶部-->
    <MainHeader :advises="true" :hasreturn="true"/>

    <mu-container>
      <div class="repair-form">
        <mu-form :model="advise" ref="form">
          <mu-form-item label="姓名" :rules="[nameRule, chineseRule]" prop="name">
            <mu-text-field v-model="advise.name" placeholder="姓名"></mu-text-field>
          </mu-form-item>

          <mu-form-item label="你的建议" :rules="[notEmptyRule, le300Rule]" prop="content">
            <mu-text-field v-model="advise.content" multi-line :rows="3" max-length="300"
                           placeholder="提出您宝贵的建议"></mu-text-field>
          </mu-form-item>

          <div class="hidename">
            <mu-checkbox v-model="advise.hideName" label="我要匿名"></mu-checkbox>
          </div>
          <div class="form-item">
            <mu-button @click="submit" full-width color="teal">提交</mu-button>
          </div>
        </mu-form>
      </div>
    </mu-container>
  </mu-flex>
</template>

<script>
  import MainHeader from './MainHeader'
  import {mapMutations} from 'vuex'
  import $http from '@/store/ajax'

  export default {
    name: "DoAdvise",
    beforeRouteEnter(to, from, next) {
      next(vm => {
        vm.showNav(false)
      })
    },
    beforeRouteLeave(to, from, next) {
      this.showNav(true);
      next()
    },
    components: {
      MainHeader
    },
    data() {
      return {
        advise: {name: null, hideName: false, content: null},
        nameRule: {validate: (val) => this.advise.hideName || val != null, message: '姓名不能为空！'},
        notEmptyRule: {validate: (val) => val != null && val.trim().length > 0, message: '必填项不能为空！'},
        chineseRule: {validate: (val) => val == null || /^[\u4e00-\u9fa5]+$/.test(val), message: '姓名只能为中文！'},
        le300Rule: {validate: (val) => val.length >= 15 && val.length <= 300, message: '最短15字，最长300字！'}
      }
    },
    methods: {
      ...mapMutations(['showNav']),
      submit() {
        let self = this;
        this.$refs.form.validate().then((result) => {
          if (result) {
            $http.post('/api/advise/add', this.advise).then(data => {
              if (data.success) {
                self.$toast.success("提交成功！");
                self.advise = {name: null, hideName: false, content: null}
              } else {
                self.$toast.warning("失败: " + data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>

<style scoped>
  .repair-form {
    padding: 12px 5px;
  }

  .mu-form-item {
    margin-bottom: 12px;
  }

  .form-item {
    margin: 12px 0;
  }

  .hidename {
    width: 100%;
    text-align: right;
    margin: 18px 0 -6px;
  }
</style>
